/***
Title: geotools_init - Initialize GeoTools Java library for Stata
Author: Unknown
Version: 1.0

Description:
    This program initializes the GeoTools Java library for use within Stata. 
    It can download the GeoTools library from SourceForge, set up paths to existing 
    GeoTools JAR files, or copy JAR files to a designated directory in Stata's plus directory.

Syntax:
    geotools_init [jarpath] , [download dir(string) plus(string)]

Options:
    download           Download GeoTools 32.0 library from SourceForge
    dir(string)        Specify directory for download (default: current directory)
    plus(string)       Specify subdirectory in Stata's plus directory to copy JAR files to

Examples:
    * Download GeoTools to the current directory
    geotools_init, download
    
    * Download GeoTools to a specific directory
    geotools_init, download dir("C:/mylibs")
    
    * Copy existing GeoTools JAR files to a subdirectory in Stata's plus directory
    geotools_init "C:/mylibs/geotools-32.0/lib/", plus(geojars)
    
    * Set up paths to existing GeoTools JAR files
    geotools_init "C:/mylibs/geotools-32.0/lib/"

Notes:
    - Requires Stata 16.0 or higher
    - Internet connection required for download option
    - Creates path_geotoolsjar.ado in Stata's plus directory when not using the plus option
    
Helper programs:
    - wrtjarpath: Writes path to JAR file to an ado file
    - removequotes: Removes quotes from file paths
    - pjar2plus: Copies JAR files to a directory in Stata's plus directory
***/


program define geotools_init
version 16.0
syntax [anything] , [download dir(string) plus(string)]

if "`download'"!=""{

	if `"`dir'"'!="" {
		mata: st_numscalar("r(exist)",direxists(`"`dir'"'))
		local exist = r(exist)
		if `exist'==0{
			di as error "Path Setting Failed..."
			di as error "dir {`dir'} NOT exist"
			exit 198
		}
	}
	if `"`dir'"'=="" local dir = c(pwd)
    local pwd `c(pwd)'
    qui cd "`dir'"
	di `"Downloading geotools-32.0-bin.zip into {browse "`dir'":`dir'}"'
    di `"Please wait for a while..."'
	copy https://jaist.dl.sourceforge.net/project/geotools/GeoTools%2032%20Releases/32.0/geotools-32.0-bin.zip geotools-32.0-bin.zip
    unzipfile geotools-32.0-bin.zip

	if `"`anything'"'!="" & "`plus'"==""{
        di as  `"Warning: {`anything'} is ignored as the jar file is downloaded to {`dir'}"'
	}
	if `"`anything'"'!="" & "`plus'"!=""{
        di as  "Warning: {`anything'} is ignored as the jar file is downloaded to {plus/`plus'}"
	}
	local anything `dir'/geotools-32.0/lib/
	qui cd "`pwd'"
}

if "`plus'"!=""{
    di "Copying geotools jars to {browse `c(sysdir_plus)'/`plus'} ..."
	pjar2plus `anything', to(`plus')
}
else{
	wrtjarpath `anything', jar(gt-main-32.0.jar) adoname(geotoolsjar)
}

end

//////////////////////////////////////

cap program drop wrtjarpath
program define wrtjarpath
version 16.0
syntax [anything] ,[jar(string)] adoname(string)

// confirm name `adoname'

if `"`anything'"'==""{
	local anything `c(pwd)'
}
else{
	removequotes,file(`anything')
	local anything `r(file)'
	mata: st_numscalar("r(exist)",direxists(`"`anything'"'))
    local exist = r(exist)
	if `exist'==0{
		di as error "Path Setting Failed..."
		di as error "dir {`anything'} NOT exist"
		exit 198
	}
}

if `"`jar'"'!=""{
	local fileexist = fileexists(`"`anything'/`jar'"')
	if `fileexist'==0{
		di as error "Path Setting Failed..."
		di as error `"`jar' NOT found in {`anything'}"'
		exit
	}
	
}



local filename =  c(sysdir_plus) + "p/path_`adoname'.ado"
file open myfile using `"`filename'"', write text replace
file write myfile "cap program drop path_`adoname'" _n
file write myfile "program define path_`adoname', rclass" _n
file write myfile "version 16.0" _n
file write myfile `"return local path `anything'"' _n
file write myfile "end" _n
file close myfile
end


cap program drop removequotes
program define removequotes,rclass
version 16
syntax, file(string) 
return local file `file'
end




cap program drop pjar2plus
program define pjar2plus
version 16.0
syntax anything, [to(string) replace]

removequotes, file(`anything')
local anything  `r(file)'
local anything = subinstr(`"`anything'"', "\", "/", .)

local pluspath = c(sysdir_plus)
if `"`to'"' == "" {
    cap mkdir "`pluspath'jar"
    local to `"`pluspath'jar"'
}
else {
    confirm name `to'
    local to `"`pluspath'`to'"'  // 将用户提供的目录名拼接到plus路径后
    mata: st_numscalar("r(exist)", direxists(`"`to'"'))
    if r(exist) == 0 {
        mkdir `"`to'"'
    }
}

mata: st_numscalar("r(exist)", direxists(`"`anything'"'))
local direxist = r(exist)

local fileexist = fileexists(`"`anything'"')

if `direxist' == 0 & `fileexist' == 0 {
    di as err `"Directory or file {`anything'} not found"'
    exit 198
}

if `direxist' {
    local files : dir `"`anything'"' files "*.jar"
    foreach file in `files' {
        copy `"`anything'/`file'"' `"`to'/`file'"', `replace'
    }
}

if `fileexist' {
    local ext = substr(`"`anything'"', -4, .)
    if lower("`ext'") != ".jar" {
        di as err "Not a jar file"
        exit 198
    }
    mata: st_local("jarfile", pathbasename(`"`anything'"'))
    copy `"`anything'"' `"`to'/`jarfile'"', `replace'
}

end

